# -*- coding: UTF-8 -*-
# base on http://www.djangosnippets.org/snippets/129/
# Template tag
from datetime import date, timedelta
from django import template
import calendar
from blogmaker.blog.models import Entry
from django.utils.translation import ugettext as _


register = template.Library()
from datetime import date, timedelta

class BlogCalendar(template.Node):
    def __init__(self,month):
        self.month = template.Variable(month)
        self._event = None
                
    def _getEvents(self, year,month):
        if self._event == None:
            self._event = Entry.objects.filter(pub_date__year=year, pub_date__month=month)
        return self._event
    
    def _post_days(self, year,month):
        post_days ={}
        for post in self._getEvents(year,month):
            day = post.pub_date.day
            articles = post_days.get(day,[])
            articles.append(post)
            post_days[day] = articles
        return post_days
    
    def render(self,context):
        try:
            fecha = self.month.resolve(context)
        except:
            fecha = date.today()
        year = fecha.year
        month= fecha.month
        post_days = self._post_days(year,month)
        month_cal = calendar.monthcalendar(year, month)
        sin_dia  = '<td class="no_date">&nbsp;</td>'
        post_day = '<td class="post_day"><a href="/%04d/%02d/%02d/"><span title="%s posts">%s</span></a></td>'
        sin_post = '<td class="no_post">%s</td>'
        table='<table id="blog_calendar"><tr class="calendar_header">'
        for header in self.week_headers():
            table=table+"<th>%s</th>"%header
        table=table+"</tr>"
        for week in month_cal:
            table=table+"<tr>"
            for day in week:
                if day == 0:
                    table=table+sin_dia
                elif post_days.has_key(day):
                    table = table + post_day % (year,month,int(day),len(post_days[day]),day)
                else:
                    table = table+sin_post % day
            table = table+"</tr>\n"
        table= table+"</table>"
        return table                            
    def week_headers(self):
        return [_("Di"),_("Dm"),_("Dx"),_("Dj"),_("Dv"),_("Ds"),_("Dg")]

@register.tag(name="post_calendar")
def do_calendar(parser,token):
    try:
        tag_name, month = token.split_contents() 
    except ValueError:
        raise template.TemplateSyntaxError, "%r tag requires exactly one arguments" % token.contents.split()[0]
    return BlogCalendar(month)
